package com.woniuxy.rabbit.kill.controller;

import com.woniuxy.rabbit.kill.util.WebSocketUtil;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

/**
 * description: ChatController <br>
 * date: 2022/1/15 6:46 下午 <br>
 * author: shesaifei <br>
 * version: 1.0 <br>
 */

@RestController
@ServerEndpoint("/woniuchat/{userName}")
public class ChatController {
    //当建立连接时
    //一个客户端对应一个session，服务器可以通过session向指定的客户端推送消息
    @OnOpen
    public void open(@PathParam("userName") String userName, Session session) {
        System.out.println("加入聊天室" + userName);
        //加入聊天室
        WebSocketUtil.MESSAGEMAP.put(userName, session);
        //向所有人发送消息
        WebSocketUtil.sendMessageToAll("欢迎：" + userName + "进入聊天室");
    }

    //当服务器接收到客户端发送的消息

    @OnMessage
    public void message(@PathParam("userName") String userName, String message) {
        //将消息转发给所有人
        WebSocketUtil.sendMessageToAll(userName + ":" + message);
    }

    //离开聊天室

    @OnClose
    public void close(@PathParam("userName") String userName) {
        //告诉所有人离开聊天室
        WebSocketUtil.sendMessageToAll(userName + "离开了聊天室");
        //
        WebSocketUtil.MESSAGEMAP.remove(userName);
    }
}
